<?php
/**
    fb_auth v0.1
    Copyright 2010 Markus Dolic (crowley@gmx.net)
    
    This file is part of the fbpost package. 
    
    fbpost is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
    fbpost is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
    You should have received a copy of the GNU General Public License
    along with fbpost. If not, see <http://www.gnu.org/licenses/>. 
**/

require_once(dirname(__FILE__)."/inc/common.php");

$addon_name = "fb_auth<a name='fb_auth'></a>";
$addon_version = "0.1";
$addon_description = "Helper addon for other fbpost components - takes care "
    . "of the Facebook OAuth process and the necessary settings. <br />";

$REDIRECT_URI = $cfgrow['siteurl'] . "admin/index.php?view=addons&fbpost_do=fbpost_gettoken#fb_auth";

// don't do anything if plugin is disabled
if (!isAddonEnabled("admin_fb_auth")) return;

$errormsg = '';
try {
    checkExtensions();
} catch (Exception $e) {
    $errormsg .= $e->getMessage() . "\n";
}

// first part of the OAuth process: process addon config form (save submitted 
// auth data etc. to DB) and redirect to OAuth URL
// (this can't be done within the addons admin page because HTTP headers are 
// already sent there)
if (isset($_GET["fbpost_do"]) and $_GET["fbpost_do"] == "fbpost_auth") {
    $certfilepath = $_POST["certfilepath"];
    $app_id = $_POST["app_id"];
    $secret = $_POST["secret"];
    $query = "UPDATE " . TABLE_FBPOST_CFG ." SET cert_file_path='$certfilepath'";
    mysql_query($query) or die(mysql_error());
    $query = "UPDATE " . TABLE_FBPOST_AUTH ." SET app_id='$app_id', secret='$secret'";
    mysql_query($query) or die(mysql_error());
    $url = FBProxy::OAUTH_URL . "?" . http_build_query(array(
        "client_id" => $app_id, 
        "scope" => "publish_stream,offline_access,manage_pages", 
        "redirect_uri" => $REDIRECT_URI), "", "&");
    header("location:" . $url);
    exit;
}

// only do anything else if we're on the addons admin page
if (isset($_GET["view"]) and $_GET["view"] == "addons") {
    
    // create tables if they do not exist yet
    $res = mysql_query("SELECT * FROM " . TABLE_FBPOST_AUTH . " LIMIT 1");
    if (!$res) {
        mysql_query("CREATE TABLE IF NOT EXISTS " . TABLE_FBPOST_AUTH . " (
                         `app_id` VARCHAR(40), 
                         `secret` VARCHAR(40), 
                         `token` VARCHAR(8192)
                     )");
    }
    if (!$res or !mysql_num_rows($res) or mysql_num_rows($res) < 1) {
        // insert default config record
    	mysql_query("INSERT INTO " . TABLE_FBPOST_AUTH . " VALUES('', '', '')");
    }

    // populate config variables from DB
    $result = mysql_query("SELECT * FROM " . TABLE_FBPOST_AUTH . " JOIN " 
        . TABLE_FBPOST_CFG . " LIMIT 1");
    while ($cfg = mysql_fetch_array($result)) {
        $app_id = $cfg["app_id"];
        $secret = $cfg["secret"];
        $token = $cfg["token"];
        $certfilepath = $cfg["cert_file_path"];
    }
    
    // second and third part of the OAuth process: convert the verification 
    // code received from facebook to a token and store it
    if (isset($_GET['fbpost_do']) and $_GET['fbpost_do'] == "fbpost_gettoken") {
        if (isset($_GET["error_reason"]))
            $errormsg .= "Could not complete authentication: " . $_GET["error_reason"] . "<br />";
        elseif (isset($_GET['code'])) {
            try {
                $token = FBProxy::getToken($app_id, $secret, $_GET["code"], 
                    $REDIRECT_URI);
            } catch (FBApiException $e) {
                $errormsg .= $e->getMessage() . "<br />";
            }
            $query = "UPDATE " . TABLE_FBPOST_AUTH ." SET token='$token'";
            mysql_query($query) or $errormsg .= "Could not store Facebook access token: " 
                . mysql_error() . "<br />";
        }
        else
            $errormsg .= "Could not complete authentication: unexpected response. <br />";
    }
    
    // build HTML for addon config page
    if (isset($errormsg) and $errormsg != "") {
        $addon_description .= formatErrorMsg($errormsg);
    }
    if (!isset($token)) $token = 'n/a';
    $addon_description .= <<<EOT
        <p><strong>Configuration</strong><br />
        These values can be found on your Facebook 
        <a href="http://www.facebook.com/developers/apps.php">apps</a> 
        page. Be sure to set "Site URL" and "Site Domain" correctly in 
        the Facebook application settings. </p>
        <form action='{$cfgrow['siteurl']}index.php?fbpost_do=fbpost_auth' method='post' accept-charset='UTF-8'>
            <table>
                <tr style='vertical-align:top;'>
                    <td>
                        SSL certificate file path: <br />
                        <span style="font-size:0.8em;">(may be required for curl - leave blank if unsure)</span>
                    </td>
                    <td><input type='text' size='40' name='certfilepath' value='{$certfilepath}' /></td>
                </tr>
                <tr style='vertical-align:top;'>
                    <td>Application ID: </td>
                    <td><input type='text' size='40' name='app_id' value='{$app_id}' /></td>
                </tr>
                <tr style='vertical-align:top;'>
                    <td>Application secret: </td>
                    <td><input type='text' size='40' name='secret' value='{$secret}' /></td>
                </tr>
                <tr style='vertical-align:top;'>
                    <td>Access token: </td>
                    <td><tt>{$token}</tt></td>
                </tr>
            </table>
            <input type='submit' value='Get token' />
        </form>
EOT;
}
?>
